import axios from 'axios'
import qs from 'qs'

let ROOT;
if (process.env.NODE_ENV === 'development') {
  ROOT = "/";//开发环境下的代理地址，解决本地跨域
} else {
  ROOT = '/';    //生产环境下的地址
}
axios.defaults.baseURL = ROOT
axios.defaults.headers.post['Content-Type'] = 'application/json;'

const fetch = (url, data, method,headers) => {
  let promise
  let option = {
    headers,
    method,
    url,
    params: {},
  }
  if (method === 'post') {
    option = { ...option, data: data }
  } else if (method === 'get') {
    option = { ...option, params: { ...option.params, ...data } }
  } else if (method === 'delete'){
    option = {...option, data: qs.stringify(data)}
  }
  promise = promise || axios(option)

  return promise.then(({ data, status, statusText }) => {
    if (status !== 200) {
      throw { data: data, statusCode: status, message: statusText }
    }
    return data
  }).then(data => ({ data })).catch(err => {
    return { err }
  })
}
let token = ''

export function codetoken() {

  if(JSON.parse(localStorage.getItem('udata'))){
    token = JSON.parse(localStorage.getItem('udata')).stateToken
  }


}
// Authorization = 'Basic '+token

export const get = (url, data = {}) => fetch(url, data, 'get',{Authorization:'Basic'+' '+token})
export const post = (url, data = {}) => fetch(url, data, 'post',{Authorization:'Basic'+' '+token})
export const del = (url, data = {}) => fetch(url, data, 'delete',{Authorization:'Basic'+' '+token})
